package com.czxy.changgou4.controller;

import com.czxy.changgou4.config.JwtProperties;
import com.czxy.changgou4.domain.AuthUser;
import com.czxy.changgou4.service.AuthService;
import com.czxy.changgou4.utils.JwtUtils;
import com.czxy.changgou4.vo.BaseResult;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public BaseResult login(@RequestBody AuthUser authUser) {
        // 1 验证码校验 code -- 一次性验证码
        // 1.1 获得用户输入验证码
        String code = authUser.getCode();
        // 1.2 获得redis存放验证码
        String key = "login" + authUser.getUsername() ;
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        // 获得验证码之后删除redis中缓存的验证码
        stringRedisTemplate.delete(key);
        // 1.3 无效验证码
        if(redisCode == null) {
            return BaseResult.error("验证码无效");
        }
        // 1.4 判断
        if(! redisCode.equalsIgnoreCase(code)) {
            return BaseResult.error("验证码错误");
        }
        // 2 登录操作
        AuthUser loginAuthUser = authService.login(authUser);

        // 3 处理结果
        if(loginAuthUser != null) {
            // 生成token
            String token = JwtUtils.generateToken(loginAuthUser, jwtProperties.getExpire(), jwtProperties.getPrivateKey());
            return BaseResult.ok("登录成功").append("loginUser",loginAuthUser).append("token",token);
        }
        return BaseResult.error("用户名或密码不匹配");
    }
}
